﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Common.Library
{
    /// <summary>
    /// 树操作帮助类
    /// </summary>
    public static class TreeHelper
    {


        /// <summary>
        /// 指定ID ，向下查询所有的子节点Id------递归获取/////包括自身
        /// </summary>
        /// <param name="id"></param>
        public static List<string> GetChildInfo<T>(this List<T> orgList, string id)
        {
            List<string> reultList = new List<string>();
            reultList.Add(id);
            //原始数据
            string strJson = JsonConvert.SerializeObject(orgList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            List<Dictionary<string, object>> dicList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(strJson);

            List<Dictionary<string, object>> chidList = dicList.FindAll(q => q["parent_id"] != null && q["parent_id"].ToString() == id).ToList();
            if (chidList.Count > 0)
            {
                foreach (var item in chidList)
                {
                    reultList.Add(item["id"].ToString());
                    strJson = JsonConvert.SerializeObject(orgList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
                    var dicListInfo = JsonConvert.DeserializeObject<List<T>>(strJson);
                    //递归获取下一级
                    reultList.AddRange(dicListInfo.GetChildInfo<T>(item["id"].ToString()));
                   
                }
            }
            return reultList;
        }


        /// <summary>
        /// 指定ID ，向下查询所有的子节点------递归获取
        /// </summary>
        /// <param name="id"></param>
        public static List<TreeInfo> GetChildTreeInfo<T>(this List<T> orgList, string id, string titleName = "", string parentIdName = "")
        {
            List<TreeInfo> reultList = new List<TreeInfo>();
            //原始数据
            string strJson = JsonConvert.SerializeObject(orgList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            List<Dictionary<string, object>> dicList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(strJson);

            //根据NodeID，获取当前子节点列表
            TreeInfo treeInfo = null;
            var parentId = parentIdName.IsNotNullOrEmpty() ? parentIdName : "parent_id";
            List <Dictionary<string, object>> chidList = dicList.FindAll(q => q[parentId] != null && q[parentId].ToString() == id).ToList();
            if (chidList.Count > 0)
            {
                foreach (var item in chidList)
                {
                    if (titleName.IsNotNullOrEmpty())
                    {
                        treeInfo = new TreeInfo()
                        {
                            id = item["id"].ToString(),
                            title = item[titleName].ToString(),
                            field = item[titleName].ToString(),
                            type = 100,
                            children = new List<TreeInfo>()
                        };
                    }
                    else
                    {
                        treeInfo = new TreeInfo()
                        {
                            id = item["id"].ToString(),
                            title = item["name"].ToString(),
                            field = item["name"].ToString(),
                            type = 100,
                            children = new List<TreeInfo>()
                        };
                    }
                    //if (item.TryGetValue("name", out  sValue))
                    strJson = JsonConvert.SerializeObject(orgList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
                    var dicListInfo = JsonConvert.DeserializeObject<List<T>>(strJson);
                    //递归获取下一级
                    treeInfo.children = dicListInfo.GetChildTreeInfo<T>(item["id"].ToString(), titleName, parentIdName);
                    reultList.Add(treeInfo);
                }
            }
            return reultList;
        }

        /// <summary>
        /// 指定ID ，向下查询所有的子节点------递归获取
        /// </summary>
        /// <param name="id"></param>
        public static List<SelectListInfo> GetSelectChildInfo<T>(this List<T> orgList, string id, string titleName = "")
        {
            List<SelectListInfo> reultList = new List<SelectListInfo>();
            //原始数据
            string strJson = JsonConvert.SerializeObject(orgList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            List<Dictionary<string, object>> dicList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(strJson);

            //根据NodeID，获取当前子节点列表
            SelectListInfo treeInfo = null;
            List<Dictionary<string, object>> chidList = dicList.FindAll(q => q["parent_id"] != null && q["parent_id"].ToString() == id).ToList();
            if (chidList.Count > 0)
            {
                foreach (var item in chidList)
                {
                    if (titleName.IsNotNullOrEmpty())
                    {
                        treeInfo = new SelectListInfo()
                        {
                            value = item["id"].ToString(),
                            name = item[titleName].ToString(),
                            children = new List<SelectListInfo>()
                        };
                    }
                    else
                    {
                        treeInfo = new SelectListInfo()
                        {
                            value = item["id"].ToString(),
                            name = item["name"].ToString(),
                            children = new List<SelectListInfo>()
                        };
                    }
                    strJson = JsonConvert.SerializeObject(orgList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
                    var dicListInfo = JsonConvert.DeserializeObject<List<T>>(strJson);
                    //递归获取下一级
                    treeInfo.children = dicListInfo.GetSelectChildInfo<T>(item["id"].ToString());
                    reultList.Add(treeInfo);
                }
            }
            return reultList;
        }

        /// <summary>
        /// 获取传入节点Id对应的子节点List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<T> GetChildList<T>(this List<T> allList, string id) where T : new()
        {
            List<T> reultList = new List<T>();

            //原始数据
            string strJson = JsonConvert.SerializeObject(allList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            List<Dictionary<string, object>> allDicList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(strJson);


            List<Dictionary<string, object>> itemList = allDicList.FindAll(q => q["id"].ToString() == id).ToList();
            var newItemList = JsonConvert.DeserializeObject<List<T>>(JsonConvert.SerializeObject(itemList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));
            reultList.AddRange(newItemList);

            //根据NodeID，获取当前子节点列表
            List<Dictionary<string, object>> chidList = allDicList.FindAll(q => q["parent_id"] != null && q["parent_id"].ToString() == id).ToList();
            if (chidList.Count > 0)
            {
                var newChidList = JsonConvert.DeserializeObject<List<T>>(JsonConvert.SerializeObject(chidList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));
                reultList.AddRange(newChidList);
                reultList.AddRange(allList.GetChildList<T>(newChidList));
            }

            return reultList;
        }

        /// <summary>
        /// 获取传入节点对应的子节点List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<T> GetChildList<T>(this List<T> allList, List<T> rootList) where T : new()
        {
            List<T> reultList = new List<T>();

            //原始数据
            string strJson = JsonConvert.SerializeObject(allList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            List<Dictionary<string, object>> allDicList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(strJson);

            //根节点数据
            string strRootJson = JsonConvert.SerializeObject(rootList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            List<Dictionary<string, object>> rootDicList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(strRootJson);

            foreach (var rootItem in rootDicList)
            {
                //根据NodeID，获取当前子节点列表
                List<Dictionary<string, object>> chidList = allDicList.FindAll(q => q["parent_id"] != null && q["parent_id"].ToString() == rootItem["id"].ToString()).ToList();

                if (chidList.Count > 0)
                {
                    var newChidList = JsonConvert.DeserializeObject<List<T>>(JsonConvert.SerializeObject(chidList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));

                    reultList.AddRange(newChidList);

                    reultList.AddRange(allList.GetChildList<T>(newChidList));
                }
            }
            return reultList;
        }

        /// <summary>
        /// 获取传入节点对应根节点的List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<T> GetParentList<T>(this List<T> allList, List<T> rootList) where T : new()
        {
            List<T> reultList = new List<T>();

            //原始数据
            string strJson = JsonConvert.SerializeObject(allList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            List<Dictionary<string, object>> allDicList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(strJson);

            //根节点数据
            string strRootJson = JsonConvert.SerializeObject(rootList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            List<Dictionary<string, object>> rootDicList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(strRootJson);

            foreach (var rootItem in rootDicList)
            {
                if (rootItem["parent_id"] != null)
                {
                    //根据NodeID，获取当前子节点列表
                    List<Dictionary<string, object>> parentList = allDicList.FindAll(q => q["id"].ToString() == rootItem["parent_id"].ToString()).ToList();

                    if (parentList.Count > 0)
                    {
                        var newParentList = JsonConvert.DeserializeObject<List<T>>(JsonConvert.SerializeObject(parentList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));

                        reultList.AddRange(newParentList);

                        reultList.AddRange(allList.GetParentList<T>(newParentList));
                    }
                }
            }
            return reultList;
        }

        /// <summary>
        /// 获取传入节点ID对应的【根】节点Id
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="allList"></param>
        /// <param name="itemId">节点ID</param>
        /// <returns></returns>
        public static T GetParentInfo<T>(this List<T> allList, string itemId) where T : new()
        {
            T reultInfo = new T();

            //原始数据
            string strJson = JsonConvert.SerializeObject(allList, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
            List<Dictionary<string, object>> allDicList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(strJson);

            Dictionary<string, object> itemInfo = allDicList.Find(q => q["id"].ToString() == itemId);

            if (itemInfo != null)
            {
                if (itemInfo["parent_id"] != null && itemInfo["parent_id"].ToString() != "")
                {
                    //根据NodeID，获取当前子节点列表
                    Dictionary<string, object> parentInfo = allDicList.Find(q => q["id"].ToString() == itemInfo["parent_id"].ToString());

                    if (parentInfo != null)
                    {
                        if (parentInfo["parent_id"] != null && parentInfo["parent_id"].ToString() != "")
                        {
                            reultInfo = allList.GetParentInfo<T>(parentInfo["id"].ToString());
                        }
                        else
                        {
                            reultInfo = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(parentInfo, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));
                        }
                    }
                }
                else
                {
                    reultInfo = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(itemInfo, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }));
                }
            }

            return reultInfo;
        }
    }
}
